import Vue from 'vue';
import MessageDialog from '@/components/MessageDialog.vue';

let MessageInstance = null;

// 创建弹窗实例
function createMessageInstance() {
  // 如果已有实例，先销毁
  if (MessageInstance) {
    document.body.removeChild(MessageInstance.$el);
    MessageInstance.$destroy();
    MessageInstance = null;
  }

  // 创建一个Vue实例作为弹窗的容器
  const DialogConstructor = Vue.extend(MessageDialog);
  MessageInstance = new DialogConstructor({
    el: document.createElement('div'),
    data() {
      return {
        visible: false,
        title: '',
        message: '',
        type: 'info',
        buttonText: '确定',
        closeOnMaskClick: true,
        onClose: () => {}
      };
    },
    methods: {
      // 覆盖组件的close方法，确保可以直接修改visible状态
      close() {
        this.visible = false;
        this.onClose();
        
        // 延迟销毁实例，确保动画效果完成
        setTimeout(() => {
          if (MessageInstance) {
            document.body.removeChild(MessageInstance.$el);
            MessageInstance.$destroy();
            MessageInstance = null;
          }
        }, 300);
      }
    }
  });

  // 将弹窗挂载到body上
  document.body.appendChild(MessageInstance.$el);
  return MessageInstance;
}

// 显示弹窗的函数
function showMessage(options) {
  const instance = MessageInstance || createMessageInstance();
  
  // 设置选项
  Object.assign(instance, options, { visible: true });
  
  return new Promise((resolve) => {
    instance.onClose = () => {
      resolve();
    };
  });
}

// 导出几个快捷方法
export default {
  // 显示普通信息弹窗
  info(message, options = {}) {
    return showMessage({
      title: options.title || '提示',
      message,
      type: 'info',
      buttonText: options.buttonText || '确定',
      closeOnMaskClick: options.closeOnMaskClick !== false
    });
  },
  
  // 显示成功信息弹窗
  success(message, options = {}) {
    return showMessage({
      title: options.title || '成功',
      message,
      type: 'success',
      buttonText: options.buttonText || '确定',
      closeOnMaskClick: options.closeOnMaskClick !== false
    });
  },
  
  // 显示错误信息弹窗
  error(message, options = {}) {
    return showMessage({
      title: options.title || '错误',
      message,
      type: 'error',
      buttonText: options.buttonText || '确定',
      closeOnMaskClick: options.closeOnMaskClick !== false
    });
  }
}; 